/* eslint-disable prettier/prettier */
import React, { Component, createRef, } from 'react';
import { View, Text, StyleSheet, SafeAreaView, Keyboard, Image, TouchableWithoutFeedback, PermissionsAndroid } from 'react-native';
import { syncPageGetFriendMsg, syncPageGetFriendMsgSeq, SetCuurentPersonalFriendPageInfo, SetPersonalFriendPageMsgItem } from "../../redux/features/appSlice"
import { connect } from 'react-redux'
import { GiftedChat, Bubble, Send, Composer, MessageText, Avatar } from 'react-native-gifted-chat';
import 'dayjs/locale/zh-cn';
import { pTx } from "../../utils/dimensions"
import { debounce } from "../../utils/useDebounce"
import { realm, schemaName } from "../../utils/schema"
import { getLaunchImageLibrary } from "../../utils/launchImageLibrary"
import Realm from "realm"
import VoicePressable from "../../components/voicePressable"
import httpApi from "../../api"
import ImageEquallyEnlarge from "../../components/imageEquallyEnlarge"
import ImageEquallyEnlargeVideo from "../../components/imageEquallyEnlargeVideo"
import PersonalBusinessCard from "../../components/personalBusinessCard"
import FriendTransferInApp from "../../components/friendTransferInApp"
import FriendGrabRedPacket from "../../components/friendGrabRedPacket"
import FriendRedPacketInApp from "../../components/friendRedPacketInApp"
import { showModal } from "../../components/rootSiblings/showModal"
import NavigateModalSelect from "../../components/rootSiblings/navigateModalSelect"
import PlayVoice from "../../components/playVoice"
import EmojiSelectorList from "../../components/emojiSelectorList"
import ImageView from "react-native-image-viewing";
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
const audioRecorderPlayer = new AudioRecorderPlayer();



export class FriendMsg extends Component {
    constructor(props) {
        super(props)
        this.state = {
            text: "",
            id: props.route.params.F,
            messages: [],
            refreshing: false,
            loading: true,
            openEmoji: false,
            isTextVoice: true,
            moreFeaturesOpen: false,
            composerText: null,
            playVoiceRefsIndex: null,
            MsgLis: [],
            currentPage: 1,
            pageSize: 1000000,
            personalFriendPageMsgItem: props.personalFriendPageMsgItem,

            images: [],
            visible: false
        }
        this.playVoiceRefs = []
        this.sendRedPacketInRefs = createRef();

    }
    componentDidUpdate(prevProps, prevState) {

        const element = this.props.personalFriendPageMsgItem
        if (element?.F) {
            this.props.SetPersonalFriendPageMsgItem({})
            const MsgLisItem = realm.objects(schemaName.FriendMsgLis).filtered(`${element._id ? '_id == ' + '"' + element._id + '"' : 'S == ' + element.S}`)[0] || {}
            this.onSend([
                {
                    ...MsgLisItem,
                    createdAt: MsgLisItem.T,
                    _id: new Realm.BSON.UUID(),
                    RedPacketIdState: 0,
                    user: {
                        _id: this.isAuthor(MsgLisItem.S) ? -1 : MsgLisItem.S,
                        avatar: httpApi.inline + (this.isAuthor(MsgLisItem.F) ? this.props.userInfo.ProfilePhoto : this.props.route.params.ProfilePhoto),
                        name: this.isAuthor(MsgLisItem.S) ? this.props.userInfo.NickName : this.props.route.params.Remark
                    }
                }
            ])
        }
    }
    frontEndPageChange() {
        const MsgLis = realm.objects(schemaName.FriendMsgLis).filtered(`F == ${this.state.id} and UserId == ${this.props.userInfo.Id}`).sorted('T', true);
        let start = (this.state.currentPage - 1) * this.state.pageSize;
        if (start >= MsgLis.length) start = 0;
        let end = this.state.currentPage * this.state.pageSize;
        if (end >= MsgLis.length) end = MsgLis.length;
        return this.formatMsgLis(MsgLis.slice(start, end));
    }
    isAuthor = (id) => id == -1
    formatMsgLis(array) {
        const list = []
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            list.push({
                ...element,
                createdAt: new Date(element.T),
                user: {
                    _id: this.isAuthor(element.S) ? -1 : element.F,
                    avatar: httpApi.inline + (this.isAuthor(element.F) ? this.props.userInfo.ProfilePhoto : this.props.route.params.ProfilePhoto),
                    name: this.isAuthor(element.S) ? this.props.userInfo.NickName : this.props.route.params.Remark
                }
            })
        }
        return list
    }
    async componentDidMount(prevProps, prevState) {
        this.props.SetCuurentPersonalFriendPageInfo(this.props.route.params)
        this.props.syncPageGetFriendMsgSeq(this.state.id, this.props.userInfo.Id)

        this.setState({
            messages: this.frontEndPageChange()
        })
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
            this.setState({ moreFeaturesOpen: false, openEmoji: false })
        });
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', Keyboard.dismiss);

        if (Platform.OS === 'android') {
            try {
                const grants = await PermissionsAndroid.requestMultiple([
                    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                    PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                    PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
                ]);
                if (
                    grants['android.permission.WRITE_EXTERNAL_STORAGE'] ===
                    PermissionsAndroid.RESULTS.GRANTED &&
                    grants['android.permission.READ_EXTERNAL_STORAGE'] ===
                    PermissionsAndroid.RESULTS.GRANTED &&
                    grants['android.permission.RECORD_AUDIO'] ===
                    PermissionsAndroid.RESULTS.GRANTED
                ) {
                } else {
                    return;
                }
            } catch (err) {
                return;
            }
        }
    }

    componentWillUnmount() {
        this.keyboardDidShowListener?.remove();
        this.keyboardDidHideListener?.remove();
        this.props.SetCuurentPersonalFriendPageInfo({})
        this.props.syncPageGetFriendMsg({})

    }

    onSend(messages = []) {
        this.setState(previousState => {
            if (messages[0]?.MT == 62) {
                const filteredRedPacket = realm.objects(schemaName.FriendMsgLis).filtered(`M == '${messages[0]?.M}' and MT == 62`)
                previousState.messages.map((item) => {
                    if (item.M == filteredRedPacket[0]?.M) {
                        item.RedPacketIdState = 1
                    }
                    return item
                })
            }
            return ({ messages: GiftedChat.append(previousState.messages, messages) })
        })
    }
    async onTextSend(messages = []) {
        try {
            var timestamp = Date.parse(new Date()) / 1000
            this.onSend(messages)
            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, {
                    F: this.state.id,
                    M: messages[0].text,
                    MT: 2,
                    T: timestamp,
                    _id: new Realm.BSON.UUID(),
                    Unread: 0,
                    UserId: this.props.userInfo.Id
                }, true);
            })
            await httpApi.sendFriendText({ message: messages[0].text, id: this.state.id, msgType: 2 })

        } catch (error) {
        }
    }
    sendFriendFile = async () => {
        try {
            let File = await getLaunchImageLibrary()
            File = File.uri ? File : File[0]
            const msgType = File.type == 'image/jpeg' ? 3 : 4
            var timestamp = Date.parse(new Date()) / 1000
            let MsgLisLength = new Realm.BSON.UUID()
            const image = await httpApi.uploadMinio(File)
            const realmItem = {
                F: this.state.id,
                M: File.fileSize + " " + image.data.FileNames[0] + " " + File.fileName,
                MT: msgType,
                T: timestamp,
                _id: MsgLisLength,
                Unread: 0,
                SendState: 1,
                UserId: this.props.userInfo.Id
            }
            this.onSend([
                {
                    ...realmItem,
                    createdAt: timestamp,
                    user: {
                        _id: -1,
                        avatar: httpApi.inline + this.props.userInfo.ProfilePhoto,
                        name: this.props.userInfo.NickName
                    }
                }
            ])
            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, realmItem, true);
            })
            await httpApi.sendFriendFile({
                id: this.state.id,
                msgType,
                srcFileName: File.fileName,
                dstFileName: image.data.FileNames[0],
                fileSize: File.fileSize
            })
        } catch (error) {
            console.log(error)
        }
    }
    sendFriendContactCard = async () => {
        try {
            const res = await httpApi.sendFriendContactCard({
                id: this.state.id,
                F: this.props.userInfo.Id,
            })
            var timestamp = Date.parse(new Date()) / 1000
            const realmItem = {
                F: this.state.id,
                M: res.data.FriendInfo,
                MT: 7,
                T: timestamp,
                _id: new Realm.BSON.UUID(),
                UserId: this.props.userInfo.Id
            }
            this.onSend([
                {
                    ...realmItem,
                    createdAt: timestamp,
                    user: {
                        _id: -1,
                        avatar: httpApi.inline + this.props.userInfo.ProfilePhoto,
                        name: this.props.userInfo.NickName
                    }
                }
            ])
            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, realmItem, true);
            })

        } catch (error) {
            console.log(error)
        }
    }
    onStopPlayDebounce = debounce(async ([item, index]) => {
        audioRecorderPlayer.stopPlayer();
        audioRecorderPlayer.removePlayBackListener();
        this.playVoiceRefs[this.state.playVoiceRefsIndex]?.onStopPlay()
        if (!item) return this.setState({ playVoiceRefsIndex: null })
        const [time, uri] = item?.M?.split(' ')
        if (this.state.playVoiceRefsIndex != index) {
            this.setState({ playVoiceRefsIndex: index })
            await audioRecorderPlayer.startPlayer(httpApi.inline + uri);
            this.playVoiceRefs[index]?.onStartPlay()
        } else {
            this.setState({ playVoiceRefsIndex: null })
        }
    }, 100, false)

    renderAvatar(props) {
        const { currentMessage } = props;
        return currentMessage.MT !== 62 && <Avatar {...props} />
    }
    renderCustomView(props, index) {
        const { currentMessage } = props;
        const M = currentMessage.M?.split(' ')
        switch (currentMessage.MT) {
            case 2:
                return <MessageText {...props} currentMessage={{ text: currentMessage.M }} />
            case 3:
                return <TouchableWithoutFeedback onPress={() => {
                    this.setState({
                        visible: true,
                        images: [
                            {
                                uri: httpApi.inline + M[1]
                            }
                        ]
                    })
                }}>
                    <View>
                        <ImageEquallyEnlarge
                            style={styles.imageEqually}
                            source={{ uri: httpApi.inline + M[1] }}
                            width={pTx(100)}
                        />
                    </View>
                </TouchableWithoutFeedback>
            case 4:
                return <ImageEquallyEnlargeVideo {...this.props} {...props} style={styles.imageEqually}
                    source={require('../../assets/image/icon36.png')}
                    width={pTx(120)}></ImageEquallyEnlargeVideo>
            case 5:
                return
            case 6:
                return <TouchableWithoutFeedback onPress={() => this.onStopPlayDebounce(currentMessage, currentMessage._id)}>
                    <View>
                        <PlayVoice
                            ref={(ref) => {
                                this.playVoiceRefs[currentMessage._id] = ref;
                            }}
                            {...this.props}
                            item={currentMessage}
                        />
                    </View>
                </TouchableWithoutFeedback>

            case 7:
                return <PersonalBusinessCard {...this.props} item={currentMessage} />
            case 8:
                return <FriendTransferInApp {...this.props} item={currentMessage} />
            case 10:
                return <FriendGrabRedPacket {...this.props} item={currentMessage} />
            case 62:
                return <View style={styles.RedPacketBox}>
                    {
                        currentMessage.S == -1 ?
                            <Text style={styles.RedPacket}>你领取了{this.props.route.params.Remark}的<Text style={[{ color: "#F35E4D" }]}>红包</Text></Text>
                            :
                            <Text style={styles.RedPacket}>{this.props.route.params.Remark}领取了你的<Text style={[{ color: "#F35E4D" }]}>红包</Text></Text>
                    }
                </View>
            default:
                break;
        }
        if (currentMessage.hongbao) {
            return (
                <Text>{currentMessage.hongbao}</Text>
            );
        }

        return null;
    };

    isCloseToTop({ layoutMeasurement, contentOffset, contentSize }) {
        const paddingToTop = 80;
        return contentSize.height - layoutMeasurement.height - paddingToTop <= contentOffset.y;
    }

    loadMoreChat() {
        // this.setRefreshing(false)
        // if (loading) {
        //     this.setLoading(false)
        //     setTimeout(() => {
        //         // this.setMessages(previousMessages => GiftedChat.prepend(previousMessages, [{ "_id": 30227, "createdAt": 1707047572917, "hongbao": "1222", "user": { "_id": 3, "avatar": "https://seopic.699pic.com/photo/60035/1283.jpg_wh1200.jpg", "name": "React Native" } }, { "_id": 30223, "createdAt": 1707047572917, "hongbao": "1222", "user": { "_id": 2, "avatar": "https://seopic.699pic.com/photo/60035/1283.jpg_wh1200.jpg", "name": "React Native" } }]))
        //         // setLoading(true)
        //     }, 1000)
        // }
    }

    renderBubble(props) {
        const { currentMessage } = props;
        return (
            <Bubble
                {...props}
                style={
                    {
                    }
                }
                textStyle={{
                    right: {
                        color: 'black',
                    },
                }}
                wrapperStyle={
                    {
                        left: {
                            backgroundColor: currentMessage.MT > 2 ? 'transparent' : '#fff',
                            paddingVertical: pTx(5),
                            borderRadius: pTx(6),
                            marginBottom: pTx(20)

                        },
                        right: {
                            backgroundColor: currentMessage.MT > 2 ? 'transparent' : '#95ec69',
                            paddingVertical: pTx(5),
                            borderRadius: pTx(6),
                            marginBottom: pTx(20)
                        },
                    }
                }
            />
        );
    };

    renderActions(props) {
        return <TouchableWithoutFeedback hitSlop={{ top: pTx(10), left: pTx(10), bottom: pTx(10), right: pTx(10) }} onPress={() => this.setState({ isTextVoice: this.state.isTextVoice ? false : true, moreFeaturesOpen: false })}>
            <Image style={[styles.footImage, { marginLeft: pTx(8) }]} source={this.state.isTextVoice ? require('../../assets/image/icon13.png') : require('../../assets/image/icon35.png')}></Image>
        </TouchableWithoutFeedback>
    };

    renderComposer(props) {
        return this.state.isTextVoice ?
            <Composer {...props}
                textInputStyle={styles.textInputStyle}
            />
            :
            <VoicePressable
                {...this.props}
                onStopPlayDebounce={() => this.onStopPlayDebounce(null, this.state.playVoiceRefsIndex)} />


    }

    renderSend(props) {
        return (
            <View style={styles.rightRenderSend}>
                <TouchableWithoutFeedback onPress={() => {
                    Keyboard.dismiss();
                    setTimeout(() => {
                        this.setState({
                            openEmoji: this.state.openEmoji ? false : true,
                            moreFeaturesOpen: false,
                            isTextVoice: true
                        })
                    }, 100)
                }}>
                    <Image style={[styles.footImage]} source={require('../../assets/image/icon12.png')}></Image>
                </TouchableWithoutFeedback>
                {!this.state.text ? <TouchableWithoutFeedback onPress={() => {
                    Keyboard.dismiss();
                    setTimeout(() => {
                        this.setState({
                            moreFeaturesOpen: this.state.moreFeaturesOpen ? false : true,
                            openEmoji: false,
                            isTextVoice: true
                        })
                    }, 100)
                }}>
                    <Image style={[styles.footImage]} source={require('../../assets/image/icon14.png')}></Image>
                </TouchableWithoutFeedback>
                    :
                    <Send
                        {...props}
                        alwaysShowSend={true}
                    >
                        <Text style={[styles.sendBtn]}>
                            发送
                        </Text>
                    </Send>
                }
            </View>
        );
    };

    renderAccessory(props) {
        return <View>
            {this.state.moreFeaturesOpen && <View style={[styles.moreFeatures]}>
                <TouchableWithoutFeedback onPress={() => this.sendFriendFile()}>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon26.png')}></Image>
                        <Text style={styles.featuresTexy}>图片</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon27.png')}></Image>
                        <Text style={styles.featuresTexy}>文件</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon28.png')}></Image>
                        <Text style={styles.featuresTexy}>语音聊天</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon25.png')}></Image>
                        <Text style={styles.featuresTexy}>视频聊天</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => this.sendRedPacketInRefs.current.setOpen(true)}>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon23.png')}></Image>
                        <Text style={styles.featuresTexy}>红包</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => showModal(<NavigateModalSelect operation={
                    [
                        { text: '站内转帐', onPress: () => this.props.navigation.navigate('friendTransferInApp', this.props.route.params) },
                        // { text: '区块链转帐', onPress: () => console.log('FriendTransferInApp') },
                    ]
                } />)}>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon29.png')}></Image>
                        <Text style={styles.featuresTexy}>转帐</Text>
                    </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => this.sendFriendContactCard()}>
                    <View style={[styles.featuresCell]}>
                        <Image style={styles.featuresImage} source={require('../../assets/image/icon24.png')}></Image>
                        <Text style={styles.featuresTexy}>名片</Text>
                    </View>
                </TouchableWithoutFeedback>
            </View>
            }
            {this.state.openEmoji && <EmojiSelectorList state={(el) => this.setState({ text: this.state.text + el.emoji })} />}
        </View>
    }

    render() {
        return (
            <SafeAreaView style={styles.mainContent}>
                <GiftedChat
                    text={this.state.text}
                    messages={this.state.messages}
                    onSend={messages => this.onTextSend(messages)}
                    user={{
                        _id: -1,
                        name: this.props.userInfo.NickName,
                        avatar: httpApi.inline + this.props.userInfo.ProfilePhoto
                    }}
                    showUserAvatar={true}
                    locale={'zh-cn'}
                    showAvatarForEveryMessage={true}
                    placeholder={''}
                    inverted={true}
                    renderAvatarOnTop={true}
                    maxInputLength={200}
                    onPressAvatar={() => {
                        console.log("11111111")
                        // this.props.navigation.navigate('logIn')
                        // this.props.navigation.navigate('fullVideo')
                    }}
                    renderAvatar={this.renderAvatar.bind(this)}
                    renderCustomView={this.renderCustomView.bind(this)}
                    renderBubble={this.renderBubble.bind(this)}
                    renderActions={this.renderActions.bind(this)}
                    renderComposer={this.renderComposer.bind(this)}
                    renderSend={this.renderSend.bind(this)}
                    renderAccessory={this.renderAccessory.bind(this)}
                    onInputTextChanged={(e) => this.setState({ text: e })}
                    minInputToolbarHeight={this.state.moreFeaturesOpen ? 120 : 28}
                    listViewProps={{
                        scrollEventThrottle: 400,
                        onScroll: ({ nativeEvent }) => {
                            Keyboard.dismiss();
                            this.setState({ moreFeaturesOpen: false, openEmoji: false })
                            if (this.isCloseToTop(nativeEvent)) {
                                this.loadMoreChat();
                            }
                        }
                    }}
                    containerStyle={styles.containerStyle}
                />
                <FriendRedPacketInApp {...this.props} ref={this.sendRedPacketInRefs} />
                <ImageView
                    images={this.state.images}
                    imageIndex={0}
                    visible={this.state.visible}
                    onRequestClose={() => this.setState({ visible: false })}
                />
            </SafeAreaView>
        )
    }
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
    SetCuurentPersonalFriendPageInfo,
    SetPersonalFriendPageMsgItem,
    syncPageGetFriendMsg,
    syncPageGetFriendMsgSeq
}

export default connect(mapStateToProps, mapDispatchToProps)(FriendMsg)

const styles = StyleSheet.create({
    mainContent: {
        flex: 1,
        backgroundColor: '#ededed',
    },
    sendBtn: {
        paddingHorizontal: pTx(12),
        marginBottom: pTx(5),
        height: pTx(30),
        fontSize: pTx(16),
        color: "#fff",
        backgroundColor: "rgba(6, 193, 97, 1)",
        borderRadius: pTx(4),
        textAlignVertical: "center"
    },
    containerStyle: {
        backgroundColor: "#EDEDED",
        paddingVertical: pTx(8),
    },
    textInputStyle: {
        fontSize: pTx(16),
        borderRadius: pTx(4),
        minHeight: 0,
        paddingVertical: pTx(5),
        paddingHorizontal: pTx(10),
        marginVertical: 0,
        backgroundColor: "#ffffff",
    },
    rightRenderSend: {
        marginHorizontal: pTx(10),
        flexDirection: "row",
        alignItems: "center"
    },
    footImage: {
        marginRight: pTx(8),
        marginBottom: pTx(5),
        width: pTx(30),
        height: pTx(30),
    },


    moreFeatures: {
        flexDirection: "row",
        flexWrap: "wrap",
        columnGap: pTx(32),
        paddingHorizontal: pTx(27),
        paddingTop: pTx(13),
    },
    featuresCell: {
        marginVertical: pTx(8),
        alignItems: "center",
    },
    featuresImage: {
        height: pTx(53),
        width: pTx(53),
    },
    featuresTexy: {
        marginTop: pTx(5),
        textAlign: "center",
        fontSize: pTx(12),
        color: "#727272"
    },

    imageEqually: {
        marginTop: pTx(5),
    },
    backgroundVideo: {
        width: pTx(150),
        height: pTx(100),
        backgroundColor: "#000"
    },
    RedPacketBox: {
        width: pTx(375) - 36,
    },
    RedPacket: {
        textAlign: "center",
        fontSize: pTx(12),
    }
});

